package cn.fx.controller;

import cn.fx.domain.Product;
import cn.fx.domain.Store;
import cn.fx.feign.StoreFeignClient;
import cn.fx.server.IProductServer;
import cn.fx.util.JsonResult;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
@Api(value = "价格API",description="商品相关的CRUD功能")
public class ProductController {

    @Autowired
    private IProductServer productServer;

    @Autowired
    private StoreFeignClient storeFeignClient;

    @PostMapping
    @ApiOperation(value = "添加商品信息")
    @SentinelResource(value = "product-add", fallback = "fallbackProductMethod")
    public JsonResult add(@RequestBody Product product){
        try {
            productServer.add(product);
            Store store = new Store();
            store.setProduct_id(product.getId());
            store.setNumber(product.getNumber());
            return storeFeignClient.save(store);
        } catch(Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("网络异常");
        }
    }

    /**
     * 熔断
     * @param id
     * @param e
     * @return
     */
    public Product fallbackProductMethod(@PathVariable("id") Long id, Throwable e){
        e.printStackTrace();
        return new Product(-1l,"熔断",-1,-1);
    }
}
